package com.bifrost.util;

import com.alibaba.fastjson.JSON;
import io.netty.channel.ConnectTimeoutException;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Date: 2017/10/23
 * Time: 10:56
 *
 * @author bifrost
 * @version 1.0.0
 */
public class HttpClientUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);
    private static PoolingHttpClientConnectionManager connMgr;
    private static RequestConfig config;
    private static final int DEFAULT_TOTLE = 20;
    private static final int MAX_TOTLE = 100;
    private static final int CONNECTION_TIMEOUT = 3000;
    private static final int CONNECTION_REQUEST_TIMEOUT = 5000;
    private static final int SCOKET_TIMEOUT = 60000 * 5;
    private static final String CODE = "UTF-8";

    static {
        connMgr = new PoolingHttpClientConnectionManager();
        connMgr.setMaxTotal(MAX_TOTLE);
        connMgr.setDefaultMaxPerRoute(DEFAULT_TOTLE);
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        configBuilder.setConnectTimeout(CONNECTION_TIMEOUT);
        configBuilder.setSocketTimeout(SCOKET_TIMEOUT);
        configBuilder.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT);
        config = configBuilder.build();
    }

    public static CloseableHttpClient getClient() {
        CloseableHttpClient httpClient =null;
        httpClient = HttpClients.custom()
                .setDefaultRequestConfig(config)
                .setConnectionManager(connMgr)
                .setRetryHandler((exception, executionCount, context) -> {
                    if (executionCount > 3) {
                        LOGGER.warn("Maximum tries reached for client http pool ");
                        return false;
                    }
                    //NoHttpResponseException 重试
                    if (exception instanceof NoHttpResponseException
                            || exception instanceof ConnectTimeoutException //连接超时重试
                            ) {
                        LOGGER.warn("NoHttpResponseException on " + executionCount + " call");
                        return true;
                    }
                    return false;
                }).build();
        return httpClient;
    }

    public static String doGet(String url, Map<String, String> param) {
        String resultString = "";
        try {
            // 创建Httpclient对象
            CloseableHttpClient httpclient = getClient();
            CloseableHttpResponse response = null;
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), CODE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param, Map<String, String> header) {
        String resultString = "";
        try {
            CloseableHttpClient httpClient = getClient();
            CloseableHttpResponse response = null;
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            if (header != null) {
                for (String headerKey : header.keySet()) {
                    httpPost.addHeader(headerKey, header.get(headerKey));
                }
            }
            // 创建参数列表
            if (param != null) {
                // 参数设置
                Set<String> keySet = param.keySet();
                List<NameValuePair> nameValuePairList = new ArrayList<>(keySet.size());
                int index = 0;
                for (String key : keySet) {
                    nameValuePairList.add(new BasicNameValuePair(key, param.get(key).toString()));
                }
                UrlEncodedFormEntity httpEntity = new UrlEncodedFormEntity(nameValuePairList, CODE);
                httpPost.setEntity(httpEntity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            Header cookieHeader = response.getFirstHeader("Set-Cookie");
            if(cookieHeader!=null){
                header.put("Cookie",cookieHeader.getValue());
            }
            //获得Cookies
            resultString = EntityUtils.toString(response.getEntity(), CODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultString;
    }

    public static String doPost(String url, Map<String, String> param) {
        return doPost(url, param, null);
    }

    public static String doPost(String url) {
        return doPost(url, null, null);
    }

    public static String doPostJson(String url) {
        return doPostJson(url, null, null);
    }

    public static String doPostJson(String url, String json) {
        return doPostJson(url, json, null);
    }

    public static String doPostJson(String url, String json, Map<String, String> header) {
        String resultString = "";
        try {
            // 创建Httpclient对象
            CloseableHttpClient httpClient = getClient();// HttpClients.custom().setDefaultRequestConfig(config).build();
            CloseableHttpResponse response = null;
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            if (header != null) {
                for (String headerKey : header.keySet()) {
                    httpPost.setHeader(headerKey, header.get(headerKey));
                }
            }
            // 创建请求内容
            if (json != null) {
                StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), CODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultString;
    }

    public static String doPostJson1(String url, String json, Map<String, String> header) {
        String resultString = "";
        try {
            // 创建Httpclient对象
            CloseableHttpClient httpClient = getClient1();// HttpClients.custom().setDefaultRequestConfig(config).build();
            CloseableHttpResponse response = null;
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            if (header != null) {
                for (String headerKey : header.keySet()) {
                    httpPost.setHeader(headerKey, header.get(headerKey));
                }
            }
            // 创建请求内容
            if (json != null) {
                StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), CODE);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.debug("HTTP请求失败:"+e);
        }
        return resultString;

    }

    private static CloseableHttpClient getClient1() {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(config)
                .setConnectionManager(connMgr)
                .setRetryHandler((exception, executionCount, context) -> {
                    if (executionCount > 3) {
                        LOGGER.warn("Maximum tries reached for client http pool ");
                        return false;
                    }
                    //NoHttpResponseException 重试
                    if (exception instanceof NoHttpResponseException
                            || exception instanceof ConnectTimeoutException //连接超时重试
                            ) {
                        LOGGER.warn("NoHttpResponseException on " + executionCount + " call");
                        return true;
                    }
                    return false;
                }).build();
        return httpClient;
    }
}
